package com.app.ytong.camera;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.ImageFormat;
import android.graphics.Matrix;
import android.hardware.Camera;
import android.graphics.SurfaceTexture;
import android.os.Build;
import android.util.Log;

import com.app.ytong.basis.Constants;
import com.app.ytong.bean.BasisBean;
import com.app.ytong.bean.LoginBean;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import my.FileUtils;
import my.http.MyHttpListener;
import my.http.MyHttpUtils;
import my.http.MyParams;

public class SlientCamera implements SurfaceTexture.OnFrameAvailableListener{

    private static final String TAG = "slient_camera";

    private Context context;

    private Camera mCamera;

    private SurfaceTexture surfaceTexture;


    public SlientCamera(Context context) {
        this.context = context;
    }

    public void onCreate() {
        Log.i(TAG, "SlientCamera, onCreate()");
        surfaceTexture = new SurfaceTexture(10);
        surfaceTexture.setOnFrameAvailableListener(this);
        //openCamere();
    }

    public int getSdkVersion() {
        return android.os.Build.VERSION.SDK_INT;
    }

    private boolean checkCameraFacing(final int facing) {
        if (getSdkVersion() < Build.VERSION_CODES.GINGERBREAD) {
            return false;
        }
        final int cameraCount = Camera.getNumberOfCameras();
        Camera.CameraInfo info = new Camera.CameraInfo();
        for (int i = 0; i < cameraCount; i++) {
            Camera.getCameraInfo(i, info);
            if (facing == info.facing) {
                return true;
            }
        }
        return false;
    }

    /**
     * 后置摄像头
     * @return
     */
    public boolean hasBackFacingCamera() {
        final int CAMERA_FACING_BACK = 0;
        return checkCameraFacing(CAMERA_FACING_BACK);
    }

    /**
     * 前置摄像头
     * @return
     */
    public boolean hasFrontFacingCamera() {
        final int CAMERA_FACING_BACK = 1;
        return checkCameraFacing(CAMERA_FACING_BACK);
    }

    public boolean openCamere() {
        try {
            // 1是前置摄像头  0 是后置摄像头
            if (hasFrontFacingCamera()){
                mCamera = Camera.open(Camera.CameraInfo.CAMERA_FACING_FRONT);

            }
            if (hasBackFacingCamera()){
                mCamera = Camera.open(Camera.CameraInfo.CAMERA_FACING_BACK);
            }

        } catch (Exception e) {
            e.printStackTrace();
            //closeCamera();
            return false;
        }
        mCamera.setDisplayOrientation(180);

        Camera.Parameters params = mCamera.getParameters();
        params.setPreviewFormat(ImageFormat.NV21);

        params.setZoom(0);//设置焦距为0

//        params.setPreviewSize(Constants.VIDEO_WIDTH, Constants.VIDEO_HEIGHT);
//        params.setPictureSize(Constants.PICTURE_WIDTH, Constants.PICTURE_HEIGHT);
        mCamera.setParameters(params);

        if (mCamera == null) {
            // Seeing this on Nexus 7 2012 -- I guess it wants a rear-facing camera, but
            // there isn't one.  TODO: fix
            //throw new RuntimeException("Default camera not available");
            Log.e(TAG, "openCamere, mCamera == null!");
            return false;
        }

        try {
            //这一步是最关键的，使用surfaceTexture来承载相机的预览，而不需要设置一个可见的view
            mCamera.setPreviewTexture(surfaceTexture);
            mCamera.startPreview();
        } catch (IOException ioe) {
            ioe.printStackTrace();
            return false;
        }
        return true;
    }

    public void tackPicture() {
        if (null == mCamera) {
            Log.e(TAG, "tackPicture(), null == mCamera");
            return;
        }
        mCamera.takePicture(mShutterCallback, null, mPictureCallback);
        //saveData = true;
        //Log.i(TAG, "takePicture after time = " + System.currentTimeMillis());
    }

    private OnFileListener onFileListener;
    private OnUrlListener urlListener;
    private String level;
    private String type;
    public void tackPicture(String level,String type, OnFileListener fileListener,OnUrlListener urlListener) {
        if (null == mCamera) {
            Log.e(TAG, "tackPicture(), null == mCamera");
            return;
        }
        this.level = level;
        this.type = type;
        this.onFileListener = fileListener;
        this.urlListener = urlListener;
        mCamera.takePicture(mShutterCallback, null, mPictureCallback);
        //saveData = true;
        //Log.i(TAG, "takePicture after time = " + System.currentTimeMillis());
    }


    private Camera.ShutterCallback mShutterCallback = new Camera.ShutterCallback() {
        @Override
        public void onShutter() {
            //playContinuousSound();
            Log.i(TAG, "mShutterCallback = " + System.currentTimeMillis());
        }
    };

    /**
     * 上传图片
     * @param file
     */
    private void uploadImage(File file){
        MyParams params = new MyParams();
        params.put("file", new File(file.getPath()));
        params.put("level",level);
        params.put("types",type);
        params.put("paths", LoginBean.getInstance().getAname());
        MyHttpUtils.postFile(Constants.URL_UPDATE_FILE, params, new MyHttpListener() {
            @Override
            public void onSuccess(int httpWhat, Object result) {
                BasisBean basisBean = (BasisBean) result;
                if(urlListener != null){
                    urlListener.onUrl(basisBean.getFilepath());
                }
                FileUtils.deleteFile(file);
            }

            @Override
            public void onFinish(int httpWhat) {
            }
        }, BasisBean.class);
    }

    public static String getPhotoFileName() {
        Date date = new Date(System.currentTimeMillis());
        SimpleDateFormat dateFormat = new SimpleDateFormat("'IMG'_yyyyMMdd_HHmmss");
        return dateFormat.format(date) + ".jpg";
    }

    private void savePicture(byte[] data){
        // 将得到的照片进行270°旋转，使其竖直
        Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
        Matrix matrix = new Matrix();
        matrix.preRotate(0);
        bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
        // 创建并保存图片文件
        File mFile = new File(Constants.DIR_CAMERA);
        if (!mFile.exists()) {
            mFile.mkdirs();
        }
        File pictureFile = new File(Constants.DIR_CAMERA, getPhotoFileName());
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(pictureFile);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            bitmap.recycle();
            fos.close();
            Log.i("TAG", "拍摄成功！");
            uploadImage(pictureFile);
            if(onFileListener != null){
                onFileListener.onResult(pictureFile);
            }

        } catch (Exception error) {
            Log.e("TAG", "拍摄失败");
            error.printStackTrace();
        }
    }

    private Camera.PictureCallback mPictureCallback = new Camera.PictureCallback() {

        @Override
        public void onPictureTaken(final byte[] data, Camera camera) {
            Log.i(TAG, "data time = " + System.currentTimeMillis());

            //final File file = new File(PHOTO_PATH, getPhotoFileName());
            //FileOutputStream output = null;
            try {
                //output = new FileOutputStream(file);
                //output.write(data);
                savePicture(data);

//                uploadImage(file);
            }catch (Exception e) {
                e.printStackTrace();
            }

            //bitmap就是拍出来的照片，可以进行需要做的操作
            //Bitmap bitmap = BitmapUtil.rotaingImageView(0, BitmapFactory.decodeByteArray(data, 0, data.length));
            //Log.i(TAG, "save time = " + System.currentTimeMillis());


        }
    };

    @Override
    public void onFrameAvailable(SurfaceTexture surfaceTexture) {
        Log.i(TAG, "onFrameAvailable, surfaceTexture.getTimestamp() = " + surfaceTexture.getTimestamp());
        //surfaceTexture.updateTexImage();
    }

    private void closeCamera() {
        Log.i(TAG, "closeCamera");
        if (null != mCamera) {
            mCamera.stopPreview();
            mCamera.release();
            mCamera = null;
        }
    }

    public void onDestroy() {
        closeCamera();
    }

    public interface OnFileListener {
        abstract void onResult(File file);
    }

    public interface OnUrlListener {
        abstract void onUrl(String url);
    }
}
